package com.example.demo.study.thread.threadPool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class ThreadPoolTest {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(8, 8, 60, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.AbortPolicy());

        List<Future<Integer>> list=new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            final  int taskId = i;
            Future<Integer> future = threadPoolExecutor.submit(() -> {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("任务" + taskId + "执行完成");
                return taskId;
            });
            list.add(future);
        }

        threadPoolExecutor.shutdown();

        try
        {
            if(!threadPoolExecutor.awaitTermination(6000,TimeUnit.MILLISECONDS))
            {
                threadPoolExecutor.shutdownNow();
            }else
            {
                for(Future<Integer> r:list)
                {
                    System.out.println("获取结果"+r.get());
                }
            }
        }catch (ExecutionException e)
        {
            threadPoolExecutor.shutdownNow();
        }





//        List<Callable<Integer>> tasks= Arrays.asList(
//                ()->{
//                    Thread.sleep(5000);
//                    return 5;
//                },
//                ()->{
//                    Thread.sleep(3000);
//                    return 3;
//                },
//                ()->{
//                    Thread.sleep(2000);
//                    return 2;
//                }
//        );
//        threadPoolExecutor.invokeAll(tasks);
    }
}
